package com.boruan.qq.zxgylibrary.ui.activities;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.service.model.DownOrderBean;
import com.boruan.qq.zxgylibrary.service.model.PayInfoResponse;
import com.boruan.qq.zxgylibrary.service.model.SettleDefaultAddressBean;
import com.boruan.qq.zxgylibrary.service.model.ShopCarDataBean;
import com.boruan.qq.zxgylibrary.service.presenter.ConfirmOrderPresenter;
import com.boruan.qq.zxgylibrary.service.view.OrderView;
import com.boruan.qq.zxgylibrary.ui.widgets.CountdownView;
import com.boruan.qq.zxgylibrary.utils.EventMessage;
import com.chinaums.pppay.unify.UnifyPayListener;
import com.chinaums.pppay.unify.UnifyPayPlugin;
import com.chinaums.pppay.unify.UnifyPayRequest;
import com.convenient.qd.core.utils.ToastUtils;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.boruan.qq.zxgylibrary.ui.activities.ConfirmOrderActivity.PAY_FAILED_RESULT_CODE;
import static com.boruan.qq.zxgylibrary.ui.activities.ConfirmOrderActivity.PAY_REQUEST_CODE;
import static com.boruan.qq.zxgylibrary.ui.activities.ConfirmOrderActivity.PAY_SUCCESS_RESULT_CODE;

/**
 * Created by 崔琦 on 2019/8/12.
 * des: 支付收银台
 */

public class PayCheckStandActivity extends BaseActivity implements OrderView {

    @BindView(R2.id.tv_pay_pharmacy_name)
    TextView tvPayPharmacyName;
    @BindView(R2.id.tv_pay_price)
    TextView tvPayPrice;
    @BindView(R2.id.tv_pay_time)
    CountdownView tvPayTime;
    @BindView(R2.id.rb_zfb)
    RadioButton rbZfb;
    @BindView(R2.id.rb_wx)
    RadioButton rbWx;
    @BindView(R2.id.rg_pay_type)
    RadioGroup rgPayType;
    @BindView(R2.id.btn_to_pay)
    Button btnToPay;


    CountDownTimer countDownTimer;

    private String type;
    private String orderId;
    private String shopName;
    private String payMoney;

    private ConfirmOrderPresenter confirmOrderPresenter;
    /**
     * 将应用注册到微信
     */
    private final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, ConstantInfo.APP_ID, true);

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_pay_check;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        registerEvent();
        if (getIntent() != null) {
            type = getIntent().getStringExtra("payFailed");
            orderId = getIntent().getStringExtra("orderId");
            shopName = getIntent().getStringExtra("shopName");
            payMoney = getIntent().getStringExtra("money");
            tvPayPharmacyName.setText(shopName);
            tvPayPrice.setText(payMoney);
        }

        confirmOrderPresenter = new ConfirmOrderPresenter(this);
        confirmOrderPresenter.onCreate();
        confirmOrderPresenter.attachView(this);

    }

    @OnClick({R2.id.tv_close_pay, R2.id.btn_to_pay})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_close_pay) {
            if (countDownTimer != null) {
                countDownTimer.onFinish();
                countDownTimer.cancel();
            }
            if (tvPayTime != null) {
                tvPayTime.releaseTime();
                tvPayTime = null;
            }
            if ("failed".equals(type)) {
                Intent intent = new Intent(PayCheckStandActivity.this, OrderDetailActivity.class);
                intent.putExtra("orderStatus", "1");
                intent.putExtra("orderId", orderId);
                startActivity(intent);
            }
            finish();

        } else if (i == R.id.btn_to_pay) {
            if (rbZfb.isChecked()) {
                //吊起支付宝支付
                confirmOrderPresenter.getPayParam(orderId, "ALIPAY_PSCAN","");
            } else if (rbWx.isChecked()) {
                //吊起微信支付
                confirmOrderPresenter.getPayParam(orderId, "WXPAY_APP","");
            }
        }
    }

    @Override
    public void onBackPressed() {
        if ("failed".equals(type)) {
            Intent intent = new Intent(PayCheckStandActivity.this, OrderDetailActivity.class);
            intent.putExtra("orderStatus", "1");
            intent.putExtra("orderId", orderId);
            startActivity(intent);
        }
        super.onBackPressed();
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void getDefaultAddressSuccess(SettleDefaultAddressBean.ResultBean settleDefaultAddressBean) {

    }

    @Override
    public void getDefaultAddressFailed(String msg) {

    }

    @Override
    public void getShopCarDataSuccess(List<ShopCarDataBean.ResultBean> shopCarDataBean) {

    }

    @Override
    public void getShopCarDataFailed(String msg) {

    }

    @Override
    public void userDownOrderSuccess(DownOrderBean.ResultBean orderBean) {

    }

    @Override
    public void userDownOrderFailed(String msg) {

    }

    @Override
    public void userPayNoticeSuccess(String msg) {

    }

    @Override
    public void userPayNoticeFailed(String msg) {

    }

    @Override
    public void getPayParamsSuccess(PayInfoResponse.ResultBean dataBean) {
        if (rbZfb.isChecked()) {
            Uri uri = Uri.parse(dataBean.getUrl());
            String payUrl = uri.getQueryParameter("imageUrl");
            Intent intent = new Intent(PayCheckStandActivity.this,GYAlipayWebActivity.class);
            intent.putExtra("url", payUrl);
            intent.putExtra("tradeId", orderId);
            startActivityForResult(intent, PAY_REQUEST_CODE);

        } else if (rbWx.isChecked()) {//微信

                               /*
                                 * 获取综合支付SDK对象
                                 * 参数：Context
                                 * */
            UnifyPayPlugin payPlugin = UnifyPayPlugin.getInstance(this);

                                    /*
                                     * 新建统一支付请求类
                                     *  */
            UnifyPayRequest payRequest = new UnifyPayRequest();

                                    /*
                                     * 初始化支付渠道(如：微信支付)
                                     * */
            payRequest.payChannel = UnifyPayRequest.CHANNEL_WEIXIN;
                                    /*
                                     * 设置下单接口中返回的数据(appRequestData)
                                     * */
            payRequest.payData = dataBean.getUrl();

            payPlugin.setListener(new UnifyPayListener() {
                @Override
                public void onResult(String resultCode, String resultInfo) {
                    if (resultCode.equals("0000")) {
                        //支付成功
                        Toast.makeText(PayCheckStandActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        //其他
                        Toast.makeText(PayCheckStandActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    //别管支付成功还是失败，都调订单详情接口获取状态，跳转到对应的订单详情
                    if (ConstantInfo.weChatPayBack){
                        confirmOrderPresenter.getOrderDetailInfo(orderId);
                        ConstantInfo.weChatPayBack = false;
                    }
                }
            });
            //开始支付
            payPlugin.sendPayRequest(payRequest);
            ConstantInfo.weChatPayBack = true;//表示调了统一下单接口，前往微信支付
        }
    }

    @Override
    public void getPayParamsFailed(String msg) {
        ToastUtils.showShort(msg);
    }

    @Override
    public void getOrderDetailSuccess(int orderStatus) {
        Intent intent = new Intent(PayCheckStandActivity.this,OrderDetailActivity.class);
        if(orderStatus == 21 || orderStatus == 30){//这里支付异常的状态，正常传订单状态
			intent.putExtra("orderStatus",orderStatus + "");
		}else{
			intent.putExtra("orderStatus","99");//支付成功以后状态变为99，支付完成，为了适配骑手配送和到店自取
		}      
        intent.putExtra("orderId",orderId);
        startActivity(intent);
        setResult(122);
        finish();
    }

    @Override
    public void getOrderDetailFailed(String msg) {
        if(TextUtils.isEmpty(msg)){
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PAY_REQUEST_CODE && resultCode == PAY_SUCCESS_RESULT_CODE) {
            //confirmOrderPresenter.userPayNotice(tradeId,"WXPay");
            Toast.makeText(PayCheckStandActivity.this, "支付成功！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(PayCheckStandActivity.this, OrderDetailActivity.class);
            intent.putExtra("orderStatus","99");//支付成功以后状态变为99，支付完成，为了适配骑手配送和到店自取
            intent.putExtra("orderId", orderId);
            startActivity(intent);
            finish();
        } else if (requestCode == PAY_REQUEST_CODE && resultCode == PAY_FAILED_RESULT_CODE) {
            int orderStatus = data.getIntExtra("orderStatus",0);
            Intent intent = new Intent(PayCheckStandActivity.this,OrderDetailActivity.class);
            intent.putExtra("orderStatus",orderStatus + "");
            intent.putExtra("orderId",orderId);
            startActivity(intent);
			finish();
        }
    }

    protected void registerEvent() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    protected void unRegisterEvent() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventMessage message) {
        if (message.getState() == EventMessage.EventState.WECHAT_PAY_SUCCESS) {
            //不知道需不需要前端修改订单状态。
            Toast.makeText(this, "支付成功！", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(PayCheckStandActivity.this, OrderDetailActivity.class);
            intent.putExtra("orderStatus", "2");
            intent.putExtra("orderId", orderId);
            startActivity(intent);
            finish();
        } else if (message.getState() == EventMessage.EventState.WECHAT_PAY_ERROR) {
            Toast.makeText(this, "支付失败，请重试！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterEvent();
    }
}
